package com.db.concurrency.factorizer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class Factorizer {
    private List<Integer> prides = new ArrayList<Integer>();
    private static final int N_ELEMENTS = 1000000;
    private AtomicInteger count = new AtomicInteger();

    public Factorizer() {
        count.set(0);
        createPrides();
    }

    private void createPrides() {
        int[] numbers = new int[N_ELEMENTS];
        for (int i = 0; i < N_ELEMENTS; ++i) {
            numbers[i] = i;
        }

        numbers[1] = 0;
        for (int s = 2; s < N_ELEMENTS; ++s) {
            if (numbers[s] != 0) {
                for (int j = s * 2; j < N_ELEMENTS; j += s) {
                    numbers[j] = 0;
                }
            }
        }
        for (int i = 0; i < N_ELEMENTS; ++i) {
            if (numbers[i] != 0) {
                prides.add(numbers[i]);
            }
        }
     }

    public synchronized int getCount() {
        return count.get();
    }

    public List<Integer> getFactors(int number) {
        count.incrementAndGet();

        List<Integer> result = new ArrayList<Integer>();
        int divResult = number;
        int i = 0;
        while (divResult != 1) {
            if (divResult % prides.get(i) == 0) {
                result.add(prides.get(i));
                divResult /= prides.get(i);
            } else {
                i++;
            }
        }
        return result;
    }
}
